import {
	baseUrl
} from './baseUrl.js'
import {
	refreshTokens
} from '@/api/token.js'

// 防止重复刷新token的标志
let isRefreshing = false;
// 存储等待重试的请求队列
let requestQueue = [];

const serve = (params) => {
	return new Promise((reslove, reject) => {
		// 执行实际请求
		const makeRequest = () => {
			// 对于包含大量数据的请求，不显示loading（如OCR上传）
			if (!params.isUpload) {
				uni.showLoading({
					title: ""
				})
			}
			// 设置请求头 - 每次都获取最新的token
			let headers = {
				'Authorization': 'Bearer ' + (uni.getStorageSync('token') || '')
			};
			// 如果是上传请求，设置合适的Content-Type
			if (params.isUpload) {
				headers['Content-Type'] = 'application/json'
			}

			console.log('发送请求，使用token:', uni.getStorageSync('token'));

			uni.request({
				url: baseUrl + params.url,
				method: params.method || 'get',
				data: params.data,
				header: headers,
				timeout: params.isUpload ? 30000 : 10000, // 上传请求超时时间更长
				success: res => {
					// 检查是否是token过期
					if (res.data && (res.data.code === '4001' || res.data.code === 4001 ||
							res.statusCode === 401)) {
						console.log('Token过期，开始刷新token');
						handleTokenExpired(params, reslove, reject);
						return;
					}

					reslove(res.data);
					if (!params.isUpload) {
						uni.hideLoading();
					}
				},
				fail: error => {
					console.error('请求失败:', error);
					reject(error);
					if (!params.isUpload) {
						uni.hideLoading();
					}
				}
			});
		};

		// 如果正在刷新token，将请求加入队列
		if (isRefreshing) {
			requestQueue.push(() => {
				makeRequest();
			});
		} else {
			makeRequest();
		}
	});
};

// 处理token过期
const handleTokenExpired = async (originalParams, resolve, reject) => {
	if (isRefreshing) {
		// 如果正在刷新，将请求加入队列
		requestQueue.push(() => {
			serve(originalParams).then(resolve).catch(reject);
		});
		return;
	}

	isRefreshing = true;

	try {
		const storedRefreshToken = uni.getStorageSync('refreshToken');

		if (!storedRefreshToken) {
			console.error('没有refreshToken，需要重新登录');
			redirectToLogin();
			reject(new Error('需要重新登录'));
			return;
		}

		console.log('开始刷新token，refreshToken:', storedRefreshToken);

		// 调用刷新token接口
		const refreshResult = await refreshTokens({
			refreshToken: storedRefreshToken
		});

		console.log('刷新token接口调用完成，结果:', refreshResult);

		if (refreshResult && refreshResult.code === '0000' && refreshResult.data) {
			// 更新token和refreshToken
			const newToken = refreshResult.data.token || refreshResult.data.accessToken;
			const newRefreshToken = refreshResult.data.refreshToken;

			if (newToken) {
				uni.setStorageSync('token', newToken);
				console.log('新token已保存:', newToken);
			}

			if (newRefreshToken) {
				uni.setStorageSync('refreshToken', newRefreshToken);
				console.log('新refreshToken已保存:', newRefreshToken);
			}

			// 重试原始请求
			console.log('开始重试原始请求');
			serve(originalParams).then(resolve).catch(reject);

			// 执行队列中的请求
			requestQueue.forEach(callback => callback());
			requestQueue = [];
		} else {
			console.error('刷新token失败:', refreshResult);
			redirectToLogin();
			reject(new Error('刷新token失败'));
		}
	} catch (error) {
		redirectToLogin();
		reject(error);
	} finally {
		isRefreshing = false;
	}
};

// 跳转到登录页
const redirectToLogin = () => {
	console.log('清除本地存储，跳转到登录页');
	uni.removeStorageSync('token');
	uni.removeStorageSync('refreshToken');
	uni.removeStorageSync('userInfo');

	uni.showToast({
		title: '登录已过期，请重新登录',
		icon: 'none'
	});

	setTimeout(() => {
		uni.reLaunch({
			url: '/pages/login/login'
		});
	}, 1500);
};

export default serve